Syntax and semantics

1 Syntax

The grammar for our language now looks like this:

\[ \begin{align} \Program \prod & \Declarations \Statements\\ \\ \Declarations \prod & \Declaration \Declarations \\ \alt & \epsilon\\ \\ \Declaration \prod & \DEF \VAR \gt{(} \Parameters \gt{)} \gt{\{} \Statements \gt{\}}\\ \\ \Parameters \prod & \VAR \gt{,} \Parameters \\ \alt & \VAR\\ \alt & \epsilon\\ \\ \Statements \prod & \Statement \Statements \\ \alt & \epsilon\\ \\ \Statement \prod & \INPUT \VAR \SEMI \\ \alt & \gt{printString} \STR \SEMI \\ \alt & \gt{printNumber} \Expr \SEMI \\ \alt & \VAR \ASSIGN \Expr \SEMI \\ \alt & \IF \gt{(} \Expr \gt{)} \gt{\{} \Statements \gt{\}} \ELSE \gt{\{} \Statements \gt{\}}\\ \alt & \IF \gt{(} \Expr \gt{)} \gt{\{} \Statements \gt{\}}\\ \alt & \WHILE \gt{(} \Expr \gt{)} \gt{\{} \Statements \gt{\}}\\ \alt & \RETURN \Expr \SEMI \\ \alt & \RETURN \SEMI \\ \\ \Args \prod & \Expr \gt{,} \Args \\ \alt & \Expr\\ \alt & \epsilon\\ \\ \Expr \prod & \Expr \gt{+} \Expr \\ \alt & \Expr \gt{-} \Expr \\ \alt & \Expr \gt{*} \Expr \\ \alt & \gt{(} \Expr \gt{)} \\ \alt & \VAR \gt{(} \Args \gt{)}\\ \alt & \INT\\ \alt & \VAR \end{align} \]

Example program

Here is an example program in our language:

def factorial(n) {
  if (n) {
    return 1;
  }
    
  return (n * factorial(n - 1));
}

input n;
print factorial(n);

2 Semantics

Our language does not have explicit declarations for local variables. Therefore, an assignment statement in a function body can be ambiguous: Is the assignment creating a new local variable; or is the assignment updating the value of a parameter?

If the variable being assigned to is a parameter of the function, then our semantics will treat the assignment as updating the parameter value. Otherwise, the assignment will be treated as creating a new local variable.